package com.springboot.frame.starter.web.intf;

import com.springboot.fram.core.encryption.AesEncrypt;
import com.springboot.frame.web.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

/**
 * @author liheng
 * @ClassName RequstHttpInputMessage
 * @Description
 * @date 2020-12-18 16:02
 */
@Slf4j(topic = "request-intf-decode")
public class RequstHttpInputMessage implements HttpInputMessage {
    private HttpHeaders headers;

    private InputStream body;

    public RequstHttpInputMessage(HttpInputMessage inputMessage,IntfEncryptionProperties intfEncryptionProperties) throws Exception {
        String unDecryptDate = IOUtils.toString(inputMessage.getBody(), "UTF-8");
        Map<String,String> map = JsonUtils.parseObject(unDecryptDate, Map.class);
        unDecryptDate=map.get(intfEncryptionProperties.getBodyKey());
        String decryptDate = AesEncrypt.decrypt(unDecryptDate,intfEncryptionProperties.getType().getAes().getKey(),intfEncryptionProperties.getType().getAes().getOffset());
        this.headers = inputMessage.getHeaders();
        this.body = IOUtils.toInputStream(decryptDate, "UTF-8");
        log.info("解密前：【{}】，解密后：【{}】:",unDecryptDate,decryptDate);
    }

    @Override
    public InputStream getBody() throws IOException {
        return this.body;
    }

    @Override
    public HttpHeaders getHeaders() {
        return this.headers;
    }
}
